#include "code.h"
#include <socket.h>
#include <in.h>

#define serveraddr   "192.168.0.107"
#define serverPort    13


static int client_ipv4_tcp()
{
    int					sockfd, n;
	char				recvline[4096 + 1];
	struct sockaddr_in	servaddr;    /* 定义结构体，存放要连接的主机信息 */

	if (argc != 2)
		err_quit("usage: a.out <IPaddress>");

	if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)   /* 创建连接 --- IPV4  指定为TCP连接 */
		err_sys("socket error");

	bzero(&servaddr, sizeof(servaddr));    /* 初始化结构体 */
	servaddr.sin_family = AF_INET;      /* 指定为 IPv4 地址*/
	servaddr.sin_port   = htons(serverPort);	/* daytime server */
	if (inet_pton(AF_INET, serveraddr, &servaddr.sin_addr) <= 0)
		err_quit("inet_pton error for %s", serveraddr);

	if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)  /* 建立连接 */
		err_sys("connect error");
	/* 读取 TCP 缓存区数据*/
	while ( (n = read(sockfd, recvline, 4096)) > 0) {
		recvline[n] = 0;	/* null terminate */
		if (fputs(recvline, stdout) == EOF)
			err_sys("fputs error");
	}
	// 当 n 为 0表示连接断开 ；或则负数的时候表示发生错误 
	if (n < 0)
		err_sys("read error");
    return 0;
}

static int client_ipv6_tcp()
{
	int					sockfd, n;
	struct sockaddr_in6	servaddr;
	char				recvline[4096 + 1];

	if (argc != 2)
		err_quit("usage: a.out <IPaddress>");

	if ( (sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)   /* 创建 Ipv6 的 TCP 套接字*/
		err_sys("socket error");

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin6_family = AF_INET6;    /* */
	servaddr.sin6_port   = htons(13);	/* daytime server */
	if (inet_pton(AF_INET6, serveraddr, &servaddr.sin6_addr) <= 0)    /* IP 转换 */
		err_quit("inet_pton error for %s", serveraddr);

	if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
		err_sys("connect error");

	while ( (n = read(sockfd, recvline, 4096)) > 0) {
		recvline[n] = 0;	/* null terminate */
		if (fputs(recvline, stdout) == EOF)
			err_sys("fputs error");
	}
	if (n < 0)
		err_sys("read error");

	return 0;
}


int server_ipv4_tcp()
{
	int					listenfd, connfd;
	struct sockaddr_in	servaddr;
	char				buff[MAXLINE];
	time_t				ticks;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);  /* 创建 IPV4 的 TCP 监听套接字*/

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(13);	/* daytime server */

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));  /*将创建的监听套接字和本机中准备监听的IP和端口进行绑定*/

	Listen(listenfd, LISTENQ);   /* 开始监听客户端的连接 */

	for ( ; ; ) {
		connfd = Accept(listenfd, (SA *) NULL, NULL);    /* 等待连接 */

        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        Write(connfd, buff, strlen(buff));

		Close(connfd);   /* 终止连接 */
	}
}



int main(int argc , char *argv[])
{
    printf("[ %s  %d ]: ",__FILE__,__LINE__);
    


    return 0;
}


